package com.gxa.weixing.pc.service.impl;

import com.gxa.weixing.core.common.ExceptionCode;
import com.gxa.weixing.core.exception.BusinessException;
import com.gxa.weixing.core.pojo.BalanceLog;
import com.gxa.weixing.core.pojo.User;
import com.gxa.weixing.core.service.impl.BaseServiceImpl;
import com.gxa.weixing.pc.mapper.BalanceLogMapper;
import com.gxa.weixing.pc.mapper.UserMapper;
import com.gxa.weixing.pc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author lirucong
 * @Date 11:02 2022/1/6
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private UserMapper userMapper = null;

    @Autowired
    private BalanceLogMapper balanceLogMapper = null;

    @Override
    public List<User> getUserListByPage(String code, String nickName, Date startTime, Date endTime, Integer page, Integer size) throws BusinessException {
        if (page == null || page <= 0 || size == null || size <= 0) {
            page = 1;
            size = 10;
        }
        Integer offset = (page - 1) * size;
        List<User> byPage = userMapper.getByPage(code, nickName, startTime, endTime, offset, size);
        if (byPage == null || byPage.size() == 0) {
            throw new BusinessException(ExceptionCode.NO_DATE);
        }
        return byPage;
    }

    @Override
    public Integer getUserListPageCount(String code, String nickName, Date startTime, Date endTime) throws BusinessException {
        List<User> byPage = userMapper.getByPage(code, nickName, startTime, endTime, null, null);
        return byPage.size();
    }

    @Override
    public void deleteById(Long id) throws BusinessException {
        if (id == null || id <= 0) {
            throw new BusinessException(ExceptionCode.PARAM_ERROR);
        }
        int i = userMapper.deleteByPrimaryKey(id);
        if (i < 1) {
            throw new BusinessException(ExceptionCode.OPERATION_FAILURE);
        }
    }

    @Override
    public List<Map<String, Object>> getWithdrawByPage(Map<String, Object> map) throws BusinessException, ParseException {
        Map<String, Object> checkKey = checkKey(map);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //处理时间
        if (checkKey.get("applyStart") != null && checkKey.get("applyEnd") != null) {
            checkKey.put("applyStart",format.parse((String)checkKey.get("applyStart")));
            checkKey.put("applyEnd",format.parse((String)checkKey.get("applyEnd")));
        }
        if (checkKey.get("checkStart") != null && checkKey.get("checkEnd") != null) {
            checkKey.put("checkStart",format.parse((String)checkKey.get("checkStart")));
            checkKey.put("checkEnd",format.parse((String)checkKey.get("checkEnd")));
        }

        Object page = checkKey.get("page");
        Object size = checkKey.get("size");
        Integer thisPage = null;
        Integer thisSize = null;
        if (page == null) {
            thisPage = 1;
        } else {
            thisPage = (Integer) page;
        }

        if (size == null) {
            thisSize = 1;
        } else {
            thisSize = (Integer) size;
        }

        List<Map<String, Object>> withdrawLog = userMapper.getWithdrawLog(checkKey);
        checkKey.put("offset", (thisPage - 1) * thisSize);
        checkKey.put("limit", thisSize);
        if (withdrawLog == null || withdrawLog.size() == 0) {
            throw new BusinessException(ExceptionCode.NO_DATE);
        }
        return withdrawLog;
    }

    @Override
    public Integer getWithdrawByPageCount(Map<String, Object> map) {
        Map<String, Object> checkKey = checkKey(map);
        checkKey.remove("offset");
        checkKey.remove("limit");
        return userMapper.getWithdrawLog(checkKey).size();
    }

    @Override
    public void  updateLogStatus(Long id, Integer status, String remark) throws BusinessException {
        if (id == null || id < 1 || status == null) {
            throw new BusinessException(ExceptionCode.PARAM_ERROR);
        }
        BalanceLog pre = balanceLogMapper.selectByPrimaryKey(id);
        if (pre == null) {
            throw new BusinessException(ExceptionCode.NO_DATE);
        }
        Integer preBalanceOrGold = pre.getBalanceOrGold();
        //判断是不是金币操作
        if (preBalanceOrGold == 0) {
            throw new BusinessException(ExceptionCode.OPERATION_EXCEPTION);
        }
        //若已经审核过就不能再审核
        if (pre.getLogStatus() == 1 || pre.getLogStatus() == 2) {
            throw new BusinessException(ExceptionCode.HAS_SHENHE);
        }
        //修改审核时间
        pre.setLogCheckTime(new Date(System.currentTimeMillis()));
        //获取这次的审核是否成功

        //获取需要修改余额的用户
        Long userId = pre.getUserId();
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw new BusinessException(ExceptionCode.NO_DATE);
        }
        if (status == 1) {//审核通过
            BigDecimal decimal = pre.getLogMoney();
            BigDecimal subtract = user.getBalance().subtract(decimal);
            user.setBalance(subtract);
            userMapper.updateByPrimaryKeySelective(user);
            //减少
            pre.setLogOperation("通过审核，余额减少" + pre.getLogMoney());

        } else if (status == 2) {//审核失败
            //获取增加减少状态
            BigDecimal decimal = pre.getLogMoney();
            BigDecimal add = user.getBalance().add(decimal);
            user.setBalance(add);
            userMapper.updateByPrimaryKeySelective(user);
            //增加
            pre.setLogOperation("审核失败，余额恢复" + pre.getLogMoney());
        }
        pre.setLogStatus(status);
        pre.setLogRemark(remark);
        userMapper.updateBalanceLog(pre);
    }

    private Map<String,Object> checkKey(Map<String,Object> map) {
        Set<String> keySet = map.keySet();
        HashMap<String, Object> hashMap = new HashMap<>();
        if (keySet.size() != 0) {
            for (String s : keySet) {
                Object o = map.get(s);
                if (!StringUtils.isEmpty(o)) {
                    hashMap.put(s,o);
                }
            }
        }
        return hashMap;
    }
}
